package com.uxsino.commons.logicSelector;

import java.util.function.Function;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class RefSelector<ObjectType> extends AbstractSelector<ObjectType> {

    @JsonProperty("name")
    @JSONField(name = "name")
    private String refName;

    @JsonIgnore
    @JSONField(serialize = false)
    private ISelector<ObjectType> ref;

    public RefSelector() {
        refName = null;
        ref = null;
    }

    public RefSelector(String refName) {
        this.refName = refName;
    }

    @Override
    public String getSelectorTypeName() {
        return "ref";
    }

    @Override
    public boolean _accept(SelectorContext<ObjectType> context) {
        if (ref != null) {
            return ref.accept(context);
        }
        return false;
    }

    public ISelector<ObjectType> getRef() {
        return ref;
    }

    public void setRef(ISelector<ObjectType> ref) {
        this.ref = ref;
    }

    public String getRefName() {
        return refName;
    }

    public boolean solved() {
        return ref != null;
    }

    @Override
    public String toString() {
        return "<ref name=\"" + refName + "\"/>";
    }

    @Override
    public String toXml() {
        return "<ref name=\"" + refName + "\"/>";

    }

    @Override
    public boolean solveReference(Function<String, ISelector<ObjectType>> finder) {
        if (refName == null)
            return false;
        ref = finder.apply(refName);
        return ref != null;
    }

}
